package com.xjrsoft.common.interceptor;

import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.BooleanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjrsoft.common.utils.SpringUtil;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.module.base.service.UserApiKeyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @Author: tzx
 * @Date: 2022/5/7 10:13
 */
@Slf4j
public class XjrSaAnnotationInterceptor implements HandlerInterceptor {
    private static final String AUTH_TOKEN_HEADER_NAME = "API-KEY";
    public XjrSaAnnotationInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String isWorkFlow = request.getHeader("isWorkFlow");
        request.setCharacterEncoding("utf-8");
        //判断是否未工作流调用 如果是工作流调用默认全放行
        String path = request.getRequestURI();
        if (path.contains("/daykpi")||path.contains("/monthkpi")){
            String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME);
            UserApiKeyService bean = SpringUtil.getBean(UserApiKeyService.class);
            String s = StringEscapeUtils.unescapeHtml4(apiKey);
            if(bean.check(s)){
                return true;
            }else if(apiKey ==null){
            }else{
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(new SaResult(10401, "请求未授权", null)));
                out.flush();
                out.close();
                return false;
            }
        }
        if (BooleanUtil.toBoolean(isWorkFlow) || SecureUtil.isAdminUser()) {
            return true;
        }

        if (!(handler instanceof HandlerMethod)) {
            return true;
        } else {
            Method method = ((HandlerMethod) handler).getMethod();
            SaStrategy.me.checkMethodAnnotation.accept(method);
            return true;
        }
    }
}